<script setup lang="ts">
import { useFormItem } from 'naive-ui/es/_mixins';
import { CloseFilled } from '@vicons/carbon';
import { isEmpty } from 'lodash-es';

import CarbonIcons from './carbon-icons.vue';
import SvgIcons from './svg-icons.vue';

import type { IconSelectProps } from '@/components/form/src/components/icon-select/types';
import { renderIcon } from '@/utils/common';

defineOptions({
  name: 'IconSelect',
});

const props = withDefaults(defineProps<IconSelectProps>(), {
  disabled: false,
  placeholder: '请选择图标',
});

const emits = defineEmits<{
  (e: 'update:value', value: string | undefined): void;
}>();

const show = ref(false);

const {
  mergedDisabledRef,
  mergedSizeRef,
} = useFormItem({
  disabled: props.disabled,
});

function handleClear() {
  emits('update:value', undefined);
}

function handleCarbonIconSelect(icon: string | undefined) {
  emits('update:value', icon);
  show.value = false;
}

function handleSvgIconSelect(icon: string | undefined) {
  emits('update:value', icon);
  show.value = false;
}
</script>

<template>
  <NPopover v-model:show="show" trigger="click">
    <template #trigger>
      <NButton
        :size="mergedSizeRef"
        :disable="mergedDisabledRef"
      >
        <div v-if="props.value">
          <div class="flex items-center justify-between">
            <component :is="renderIcon(props.value, 24, '2px')" />
            <NIcon class="ml-4" :component="CloseFilled" size="12" @click="handleClear" />
          </div>
        </div>
        <div v-else class="text-gray-300">
          {{ isEmpty(props.placeholder) ? '请选择图标' : props.placeholder }}
        </div>
      </NButton>
    </template>

    <NTabs type="segment" animated>
      <NTabPane name="single" tab="单色图标">
        <CarbonIcons :icon="props.value" @select="handleCarbonIconSelect" />
      </NTabPane>
      <NTabPane name="multiple" tab="多色图标">
        <SvgIcons @select="handleSvgIconSelect" />
      </NTabPane>
    </NTabs>
  </NPopover>
</template>
